import axios from 'axios'
import store from '@/store'
import Vue from "vue"
import router from '@/router'
import { getToken, setToken, setHasLogin, getUserId } from '@/libs/util'

const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) { store.dispatch('addErrorLog', info) }
}

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'yjyToken': getToken(),
        'yjyUserId': getUserId(),
        'yjyDevAgent': navigator.userAgent,//设备型号
        'yjyDevSystem': 'backstage',//设备系统
      }
    }
    return config
  }
  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      //  Spin.hide()
      Vue.prototype.$loading.hide()

    }
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        if (config.isLoading != 0) {
          Vue.prototype.$loading.show()//loading
        }

      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      // debugger
      if (res.data.code != 200 && res.data.code != 201 && res.data.code != 202 && res.data.code != 203 && res.data.code != 204) {
        Vue.prototype.$Message.error(res.data.msg)
      }
      if (res.data.code != 401) {
        const { data, status } = res
        return { data, status }
      } else {
        //Vue.prototype.$Message.warning(res.data.msg)
        setTimeout(() => {
          setToken('')
          setHasLogin('')
          router.replace({
            path: '/login',
            query: { redirect: router.currentRoute.fullPath }
          })
        }, 500)
      }

    }, error => {
      Vue.prototype.$Message.error("服务器没响应");
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      // addErrorLog(errorInfo) 
      return Promise.reject(error)
    })
  }
  request(options) {
   
    const instance = axios.create();
    let headers = Object.assign(this.getInsideConfig().headers, options.headers);
    options.headers = headers;
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
